/*
 * @Author: your name
 * @Date: 2021-05-23 17:55:15
 * @LastEditTime: 2021-06-06 14:38:51
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /xiangpan-admin/src/pages/vip/rechargeModal/index.tsx
 */
/*
 * @Author: your name
 * @Date: 2021-05-19 17:22:23
 * @LastEditTime: 2021-05-23 00:20:52
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /xiangpan-admin/src/pages/home/scheduModal/index.tsx
 */
import { IFormTypeEnum } from '@/components/form/formComponent';
import {
  Button,
  Col,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
  Space,
  message,
} from 'antd';
import HeaderForm from '@/components/form';

import React from 'react';
import { IForm } from '../../../components/form/formComponent';
import form from '@/components/form';
import { EPermission, VipLevelList } from '@/enum';
import { globalModel } from '@/pages/globalModel';
import { PlusOutlined, CloseOutlined } from '@ant-design/icons';
import './index.less';
import useObj from '@/use/useObj';
import { useRequest } from '@/.umi/plugin-request/request';
import {
  get_store_projects,
  get_user_list,
  vip_user_right,
} from '@/services/pages';
import initPagination from '@/use/initPagination';
import { useEffect } from 'react';
import { observer } from 'mobx-react';

interface IProps {
  visible: boolean;
  close: () => void;
  refresh: () => void;
  row?: any;
}
const RechargeModal = (props: IProps) => {
  const [obj, setObj] = useObj({
    vip_rights: [{ project_id: '', count: null }],
  });
  const [form] = Form.useForm();
  const { data, error, loading } = useRequest(() => get_store_projects({}));

  useEffect(() => {
    form.setFieldsValue({
      vip_level: props.row?.vip_level || null,
      vip_rights: JSON.parse(props.row?.vip_rights)?.filter(
        (r) => r.store_id === globalModel.userInfo?.store_id,
      ),
    });
    return () => {
      form.resetFields();
    };
  }, []);

  const getWithoutVipRights = () => {
    return JSON.parse(props.row?.vip_rights)?.filter(
      (r) => r.store_id !== globalModel.userInfo?.store_id,
    );
  };

  const onFinish = async (values) => {
    console.log(values, 'values==');

    await form.validateFields();
    await vip_user_right({
      user_id: props.row.user_id,
      ...values,
      balance: values.balance * 100,
      vip_level: values.vip_level ? values.vip_level : 0,
      vip_rights: [...values.vip_rights, ...getWithoutVipRights()],
    });
    message.success('充值成功');
    props.close();
    props.refresh();
  };
  console.log(VipLevelList, 'VipLevelList=');

  return (
    <Modal
      maskClosable={false}
      visible={props.visible}
      title={'会员充值'}
      footer={null}
      onCancel={props.close}
      width={600}
      className="rechargeModal"
    >
      <Form
        form={form}
        labelCol={{ span: 4 }}
        onFinish={onFinish}
        onValuesChange={(value, allValues) => {}}
      >
        <Form.Item label="会员名称">
          <Input disabled value={props.row?.user_name} />
        </Form.Item>
        <Form.Item
          label="充值金额"
          name="balance"
          rules={[
            {
              required: true,
              validator: (rule, value) => {
                if (value === undefined || value < 0) {
                  return Promise.reject('请输入正确的充值金额');
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <InputNumber
            placeholder="请输入充值金额"
            style={{ width: '177px' }}
          />
        </Form.Item>

        <Form.Item label="会员等级" name="vip_level">
          <Select
            optionFilterProp="label"
            showSearch
            allowClear
            placeholder="请选择会员等级"
          >
            {VipLevelList?.map((row, index) => {
              return (
                <Select.Option key={index} value={row.key} label={row.label}>
                  {row.label}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.List name="vip_rights">
          {(fields, { add, remove }) => {
            if (fields.length === 0) {
              add();
            }
            return (
              <>
                {fields.map(({ key, name, fieldKey, ...restField }) => (
                  <Row gutter={15} key={key}>
                    <Col span={12}>
                      <Form.Item
                        label="赠送项目"
                        {...restField}
                        name={[name, 'project_id']}
                        fieldKey={[fieldKey, 'project_id']}
                        labelCol={{ span: 8 }}
                      >
                        <Select
                          optionFilterProp="label"
                          showSearch
                          allowClear
                          placeholder="请选择赠送项目"
                        >
                          {data?.results?.map((row, index) => {
                            return (
                              <Select.Option
                                value={row.project_id}
                                key={index}
                                label={row.project_name}
                              >
                                {row.project_name}
                              </Select.Option>
                            );
                          })}
                        </Select>
                      </Form.Item>
                    </Col>
                    <Col span={9}>
                      <Form.Item
                        label="数量"
                        labelCol={{ span: 6 }}
                        {...restField}
                        name={[name, 'count']}
                        fieldKey={[fieldKey, 'count']}
                        rules={[
                          {
                            required: true,
                            validator: (rule, value) => {
                              if (value < 1) {
                                return Promise.reject('请输入正确的数量');
                              }
                              return Promise.resolve();
                            },
                          },
                        ]}
                      >
                        <InputNumber
                          placeholder="请输入数量"
                          style={{ width: '100%' }}
                        />
                      </Form.Item>
                    </Col>
                    <Col span={2}>
                      <Space className="opt-project">
                        <PlusOutlined onClick={() => add()} />
                        <CloseOutlined onClick={() => remove(name)} />
                      </Space>
                    </Col>
                  </Row>
                ))}
              </>
            );
          }}
        </Form.List>
        <Form.Item>
          <Button htmlType="submit" type="primary" style={{ marginLeft: 80 }}>
            确定
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default observer(RechargeModal);
